package com.iconmaker.command;

import java.util.ArrayList;

import com.iconmaker.controller.CanvasActivity;
import com.iconmaker.model.Conf;
import com.iconmaker.model.Position;
import com.iconmaker.model.State;
import com.iconmaker.view.PixcelView;

public class BucketCommand implements ICommand {
	private int newColor;
	private int oldColor;
	private int x;
	private int y;
	private ArrayList<PixcelView> pixcels;
	private ArrayList<Position> positions = new ArrayList<Position>();
	private boolean isValid = true;
	
	public BucketCommand(int x, int y, int color) {
		this.newColor = color;
		this.x = x;
		this.y = y;
	}
	
	@Override
	public boolean doCommand() {
		if((x <= Conf.countOfRowPixcel - 1) && (x >= 0) && (y <= Conf.countOfColumnPixcel - 1) && (y >= 0)) {
			if(newColor != State.canvasState[x][y]) {
				oldColor = State.canvasState[x][y];
				spread(x, y);
				pixcels = CanvasActivity.getContext().getView(positions);
				
				if(pixcels != null) {
					for(PixcelView view : pixcels) {
						view.setBackgroundColor(newColor);
					}
					
					return true;
				} else {
					isValid = false;
					return false;
				}
			} else {
				isValid = false;
				return false;
			}
		} 
		
		isValid = false;
		return false;
	}
	
	@Override
	public void unDoCommand() {
		if(isValid) {
			if(pixcels != null) {
				for(PixcelView view : pixcels) {
					view.setBackgroundColor(oldColor);
				}
			}
			
			if(positions != null) {
				for(Position position : positions) {
					State.canvasState[position.getX()][position.getY()] = oldColor;
				}
			}
		}
	}
	
	public void spread(int x, int y) {
		if(oldColor == State.canvasState[x][y]) {
			State.canvasState[x][y] = newColor;
			positions.add(new Position(x, y));
			
			if(x < Conf.countOfRowPixcel - 1) {
				if(State.canvasState[x + 1][y] == oldColor)
					spread(x + 1, y);
			}
			if(x > 0) {
				if(State.canvasState[x - 1][y] == oldColor)
					spread(x - 1, y);
			}
			if(y < Conf.countOfColumnPixcel - 1) {
				if(State.canvasState[x][y + 1] == oldColor)
					spread(x, y + 1);
			}
			if(y > 0) {
				if(State.canvasState[x][y - 1] == oldColor)
					spread(x, y - 1);
			}
		}
	}
}
